
var workbench = function() {
	//地图
	var map;
	return {
		/**
		 * 初始化页面元素
		 */
		init : function() {
			//初始化客户下拉框
			monitorConsoleDetailCount = 0;
			//清除定时器，避免用户多次点击同一目录生成多个定时器
			if(monitorConsoleRefreshTimer){
				window.clearInterval(monitorConsoleRefreshTimer);
			}
			
			workbench.initCustomerSelect();
			//根据所选择客户查询电池报警信息
			$("#customer_select").on("change", function(e) {
				workbench.handleCountInfoPanel();
				workbench.handleLocationInfo();
				//$("#btn_query").click();
			});
			
			$(function(){
				/*$('.cusInfoId').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('#btn_query').click();
					}
				});
				
				$("#alertName_select").change(function(){
				    $('#btn_query').click();
				})
				
				$("#alertLevel_select").change(function(){
					$('#btn_query').click();
				})*/
				
				//地图keyup事件
				$('#queryPackCode').bind('keyup',function(e){
					if(e.keyCode == '13'){
						workbench.getLocationInfo();
					}
				})
			});
			
			//处理页面刷新
			var cycle = util.getRefreshCycle("REFRESH_CYCLE");
			//启用页面刷新
			monitorConsoleRefreshTimer = window.setInterval(function(){
				App.blockUI($("#refreshZone"));//开始loading
				workbench.handleCountInfoPanel();
				workbench.getLocationInfo();
				//$("#btn_query").click();
			},cycle);

			/*var tableId = "alert_table";
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "alertName",
					"value" : $("#alertName_select").val()
				});
				aoData.push({
					"name" : "levelName",
					"value" : $("#alertLevel_select").val()
				});
				aoData.push({
					"name" : "alertTime",
					"value" : $("#datepicker").val()
				});
				aoData.push({
					"name" : "alertInfo",
					"value" : $("#cusInfoId").val().trim()
				});
				aoData.push({
					"name" : "cusId",
					"value" : $("#customer_select").val()
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});

			}

			$("#alert_table").DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "monitor/workbench/getPackAlertInfoList1.mvc",
				"fnServerData" : queryData,
				"pageLength" : 6,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ 
				{	
					"data":"index",//序号
					"bSortable" : false,
            		"render":function(data,type,row,meta){
            			var startIndex = meta.settings._iDisplayStart;
             			return startIndex+meta.row+1;
         			}
				},
				{
					"data" : "packCode",
					"bSortable" : false,
					"defaultContent": ""
				}, 
				{
					"data" : "clientId",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "customer",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "alertName",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "levelName",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "alertTime",
					"bSortable" : false,
					"defaultContent": ""
				},     
				],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected(tableId);
				}
			});*/

			//查询
			/*$("#btn_query").click(function() {
				var table = $("#alert_table").DataTable();
				table.draw(true);
				//getPackAlertInfoList();
			});*/
			
			function getPackAlertInfoList() {
				$("#alert_info_table_processing").removeClass("hide");
				var aoData = [];
				aoData.push({
					"name" : "alertName",
					"value" : $("#alertName_select").val()
				});
				aoData.push({
					"name" : "levelName",
					"value" : $("#alertLevel_select").val()
				});
				aoData.push({
					"name" : "alertTime",
					"value" : $("#datepicker").val()
				});
				aoData.push({
					"name" : "alertInfo",
					"value" : $("#cusInfoId").val().trim()
				});
				aoData.push({
					"name" : "cusId",
					"value" : $("#customer_select").val()
				});
				$.ajax({
					"type" : "post",
					"url" : "monitor/workbench/getPackAlertInfoList.mvc",
					"async" : true,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						$("#alert_info_table tbody").html("");
						packAlertInfoList = resp.aaData;
						$(".alert-content-list").scrollTop(0);
						nextPage = 2;
						if (packAlertInfoList.length == 0) {
							$("#alert_info_table tbody").append('<tr><td colspan="7" class="dataTables_empty">没有数据</td></tr>');
						} else {
							totalPage = Math.ceil(packAlertInfoList.length/pageSize);
							loadPackAlertInfo(1);
						}
						$("#alert_info_table_processing").addClass("hide");
					}
				});
			}
			
			$(".alert-content-list").on('scroll',function () {
				var winHeight = $(".alert-content-list").height();
		    	var scrollTop = $(".alert-content-list").scrollTop();
		    	var scrollHeight = $(".alert-content-list")[0].scrollHeight;
		    	if (scrollHeight - (scrollTop + winHeight) < 100 && nextPage <= totalPage) {
		    		loadPackAlertInfo(nextPage++);
		    	}
	        });
			
			function loadPackAlertInfo(page) {
				var startRec = pageSize * (page - 1);
				var endRec = (pageSize * page) > packAlertInfoList.length ? packAlertInfoList.length : (pageSize * page);
				
				var html = "";
				for (; startRec < endRec; startRec++) {
					var packAlertInfo = packAlertInfoList[startRec]
					var category = "bg-orangedeep";
					if (packAlertInfo.category == '1') {
						category = "bg-orange";
					}
					html += '<tr>' +
								'<td><div><span class="' + category + '"></span></div></td>' +
								'<td><div>' + packAlertInfo.packCode + '</div></td>' +
								'<td><div>' + packAlertInfo.clientId + '</div></td>' +
								'<td><div>' + packAlertInfo.customer + '</div></td>' +
								'<td><div>' + packAlertInfo.alertName + '</div></td>' +
								'<td><div>&nbsp;' + packAlertInfo.levelName + '</div></td>' +
								'<td><div>' + packAlertInfo.alertTime + '</div></td>' +
						    '</tr>';
				}
				$("#alert_info_table tbody").append(html);
			}
			
		},
		
		/**
		 * 根据选择客户加载统计信息
		 */
		handleCountInfoPanel:function(){
				$.ajax({
					'type':'post',
					'url':'monitor/workbench/getCustomPackAlertInfo.mvc',
					'dataType':'json',
					'async':true,
					'data':{'cusId':$("#customer_select").val()},
					'success':function(data){
						//debugger
						$("#totalNum").empty().append(data.total);
						if(data.todayAlertNum >99){
							$("#alertNum").empty().append("99+");
						} else {
							$("#alertNum").empty().append(data.todayAlertNum);
						}
						$("#chargingNum").empty().append(data.charging);
						$("#unChargingNum").empty().append(data.unCharging);
						$("#powerFail").empty().append(data.powerFail);
						if(data.barChartData.length>0){
							$(".chart_div").show();
							workbench.setBarChart(data.barChartData);
						    workbench.setPieChart(data.pieChartData);
						} else {
							$(".chart_div").hide();
						}
					},
					'error':function(msg){
						App.blockUI($("#refreshZone"));
						console.log("error");
					}
				})
		},

		_getBoundary:function(e){ 
			//debugger
			var name ;      
			var bdary = new BMap.Boundary();
			var geocoder = new BMap.Geocoder();
			geocoder.getLocation(new BMap.Point(e.point.lng, e.point.lat),function(result){
				if(result){
					name = result.address;
				}
			});
			bdary.get(name, function(rs){       //获取行政区域
				map.clearOverlays();        //清除地图覆盖物       
				var count = rs.boundaries.length; //行政区域的点有多少个
				if (count === 0) {
					//alert('未能获取当前输入行政区域');
					return ;
				}
	          	var pointArray = [];
				for (var i = 0; i < count; i++) {
					var ply = new BMap.Polygon(rs.boundaries[i], {strokeWeight: 2, strokeColor: "#ff0000"}); //建立多边形覆盖物
					map.addOverlay(ply);  //添加覆盖物
					pointArray = pointArray.concat(ply.getPath());
				}    
				map.setViewport(pointArray);    //调整视野  
				//addlabel();               
			});   
		},


		
		/**
		 * 处理电池位置信息
		 */
		handleLocationInfo:function(){
			
				map = new BMap.Map("mapZoneDiv");
				//map.addEventListener("mousemove",function(e){
				//	workbench._getBoundary(e);
				//});
				map.centerAndZoom(new BMap.Point(116.417854,39.921988),6);//默认中心点
				map.enableScrollWheelZoom(true);//缩放
                //向地图中添加缩略图控件  
                var ctrlOve = new window.BMap.OverviewMapControl({  
                    anchor: BMAP_ANCHOR_BOTTOM_RIGHT,  
                    isOpen: 1  
                });  
                map.addControl(ctrlOve);
                //向地图中添加比例尺控件  
                var ctrlSca = new window.BMap.ScaleControl({  
                    anchor: BMAP_ANCHOR_BOTTOM_LEFT  
                });  
                map.addControl(ctrlSca); 
                
                //添加地图自定义控件
                function queryPackCode(){
              	  this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
                    this.defaultOffset = new BMap.Size(10, 10); // 距离左上角位置
                    this.searchBox = document.createElement("input");// 搜索
                    this.searchBox.setAttribute("type", "text"); 
                    this.searchBox.setAttribute("placeHolder","请输入电池ID");
                }
                queryPackCode.prototype = new BMap.Control();
                queryPackCode.prototype.initialize = function(map){
                  // 创建一个DOM元素
                  var div = document.createElement("div");
                  var txt = this.searchBox;
                  txt.className = "form-control";
                  txt.setAttribute("id", "queryPackCode");
                  div.appendChild(txt);
                  // 添加DOM元素到地图中
                  map.getContainer().appendChild(div);
                  // 将DOM元素返回
                  return div;
                }
                // 创建控件
                var queryPackCodeCtrl = new queryPackCode();
                // 添加到地图当中
                map.addControl(queryPackCodeCtrl);
                
                workbench.getLocationInfo()
		},
		
		
		/**
		 *  根据选中的电池id去获取位置信息 并在地图中绘制  
		 */
		getLocationInfo:function(){
			map.centerAndZoom(new BMap.Point(116.417854,39.921988),6);//默认中心点
			$.ajax({
				'type':'post',
				'url':'monitor/workbench/getPackLocationInfo.mvc',
				'dataType':'json',
				'async':true,
				'data':{'packCodes':$("#queryPackCode").val(), 'cusId':$("#customer_select").val()},
				'success':function(data){
					//清空上次标注
					map.clearOverlays();
					//debugger
					if(data.length>0){
						var points = new Array();
						var markers = new Array();
						for ( var int = 0; int < data.length; int++) {
							var new_point = new BMap.Point(data[int].longitude, data[int].latitude);
							new_point.info = data[int];
							points.push(new_point);
							markers.push(new BMap.Marker(new_point));
						}
						var markerClusterer = new BMapLib.MarkerClusterer(map, {markers:markers}); 
						markerClusterer.setMaxZoom(8);
						markerClusterer.setGridSize(100);
						var options = {
				                //size: BMAP_POINT_SIZE_SMALL,
				                size: BMAP_POINT_SIZE_BIG,
				                shape: BMAP_POINT_SHAPE_WATERDROP
				            };
			            var pointCollection = new BMap.PointCollection(points, options);  // 初始化PointCollection
			            pointCollection.addEventListener('click', function (e) {
			    			var point = new BMap.Point(e.point.lng, e.point.lat); 
			    			var _facName = e.point.info.facName;
							_facName = e.point.info.facName == null?'未关联厂区':e.point.info.facName;
			    			var lableInfo ="<table><tr><td><b>最后采集时间：</b>"+e.point.info.gatherTime+"</td><td><b>采集终端ID：</b>"+e.point.info.clientId+"</td></tr>" +
							"<tr><td><b>电池ID：</b>"+e.point.info.packCode+"</td><td><b>SOC：</b>" + e.point.info.soc + "</td></tr>" +
							"<tr><td><b>总电压：</b>" + e.point.info.vol + "V</td><td><b>总电流：</b>" + e.point.info.current +"A</td></tr>" +
							"<tr><td><b>客户：</b>" + e.point.info.cusName + "</td><td><b>所属厂区：</b>" + _facName + "</td></tr>" +
							"<tr><td><b>地理位置：</b>"+workbench.decodeAddress(e.point.lng, e.point.lat)+"</td><td></td></tr>" +
							"<tr><td></td><td><a style=\"cursor:pointer;\" onclick=\"workbench.showDetail('"+e.point.info.packCode+"','" + e.point.info.clientId + "')\">查看详情</a></td></tr>" +
								"</table>";
			    			
			    			var infowindow = new BMap.InfoWindow(lableInfo);
			    			map.openInfoWindow(infowindow, point);
			            });
				        map.addOverlay(pointCollection);  // 添加Overlay
					}
					App.unblockUI($("#refreshZone"));//停止loading
					
				},
				'error':function(msg){
					App.unblockUI($("#refreshZone"));//停止loading
					console.log("error");
				}
			})
		},
		
		/**
		 * 根据经纬度解析地理位置
		 * @param lng 经度
		 * @param lat 维度
		 */
		decodeAddress:function(lng, lat){
			var address = "";
			$.ajax({
				type:'post',
				url:'monitor/workbench/decodeAddress.mvc',
				async:false,
				data:{'lng':lng,'lat':lat},
				dataType:'json',
				success:function(data){
					address = data.address;
				}
			})
			return address;
		},
		/**
		 *  跳转道监控详情页面
		 * @param p 电池id
		 * @param c 终端id
		 */
		showDetail:function(p, c){
			util.showContent("pages/monitor/packDataMonitor_detail.jsp",{'clientId':c,'packCode':p});
		},
		
		/**
		 * 初始化客户选择下拉框
		 * @returns
		 */
		initCustomerSelect:function() {
			$.ajax({  
		           type: 'POST',  
		           url: "monitor/workbench/getAlertTableQuerySelectOption.mvc", //url    
		           dataType: "json",
		           async:false,
		           ContentType: "application/json; charset=utf-8",  
		           success: function (data) {
		           //初始化select2
		           var dataCustomer = data.customers;
		           //util.createOption("alertName_select", "全部", data.alertNameList);
		           //util.createOption("alertLevel_select", "全部", data.alertLevelList);
		           $('#customer_select').append('<option value="">全部</option>');
		           $.each(dataCustomer,function(index,value){
	          		     $('#customer_select').append('<option value="' + dataCustomer[index].id+ '">'+dataCustomer[index].text+'</option>');
	          		 });
		           	$("#customer_select").select2({
		          	     placeholder:'请选择客户',//默认文字提示
		          	     language: "zh-CN",//汉化
		          	     allowClear: true//允许清空
		          	});
		           	$("#customer_select").select2().val('').trigger("change");
		           	workbench.handleCountInfoPanel();
					workbench.handleLocationInfo();
					//$("#btn_query").click();
		           },  
		           error: function (msg) {  
		        	   util.showModal("#_alertModal", "获取所属客户失败！");
		           }  
			});
		},
		
		/**
		 * 设置柱形图
		 * @param data 数据
		 */
		setBarChart:function(data){
			var dataX = new Array();
			var dataY = new Array();
			for (var index = 0; index < data.length; index++) {
				dataX.push(data[index]['x']);
				dataY.push(data[index]['y']);
			}
			option = {
					    tooltip: {
					        trigger: 'axis'	
					    },
					    legend: {
					        data:['报警数']
					    },
					    toolbox: {
					        show: false
					    },
					    xAxis:  {
					        type: 'category',
					        splitLine:{show:true},
					        data: dataX
					    },
					    yAxis: {
					        type: 'value',
					        splitLine:{show:true},
					        axisLabel: {
					            formatter: '{value}'
					        }
					    },
					    series: [{
					    	    name:'报警数',
					            type:'bar',
					            data:dataY,
					            barWidth: '40%',
					            itemStyle: {
					            	normal: {
							            label : {
			                                  show: true,
			                                  position: 'top'
			                              }
					            	}
			            		}
					        }]
					};
			    var myChart = echarts.init(document.getElementById("alert_bar_chart"),'macarons');
			    myChart.setOption(option,true);
		},
		
		/**
		 * 设置饼状图
		 * @param data 数据
		 */
		setPieChart:function(data){
			var dataX = new Array();
			var dataY = new Array();
			for (var index = 0; index < data.length; index++) {
				dataX.push(data[index]['x']);
				dataY.push({value:data[index]['y'],name:data[index]['x']});
			}
			option = {
			    tooltip : {
			        trigger: 'item',
			        formatter: "{a} <br/>{b} : {c} ({d}%)"
			    },
			    legend: {
			        left: 'center',
			        data: dataX
			    },
			    series : [
			        {
			        	name: '告警级别',
			            type: 'pie',
			            radius : '55%',
			            center: ['50%', '60%'],
			            data: dataY,
			            itemStyle:{ 
				            normal:{ 
				                  label:{ 
				                    show: true, 
				                    formatter: '{b} : {c} ({d}%)' 
				                  }, 
				                  labelLine :{show:true} 
				                } 
			            } 
			        }
			    ]
			};
			var myChart = echarts.init(document.getElementById("alert_pie_chart"),'macarons');
			myChart.setOption(option,true);
		}
	};
}();
